<template>
  <x-main>
    <x-box title="订单标签">
      <view class="x-container">
        <view class="x-label">订单标签</view>
        <view class="x-small-top">
          <x-radio-button v-model="state.form.orderTag" :list="ORDER_TAG"></x-radio-button>
        </view>
      </view>

      <x-select :border="false" v-model="state.form.storeId" type="remote" options="STORE" label="所属门店"></x-select>
    </x-box>

    <view class="box">
      <x-box title="费用设置">
        <x-select label="收款期数" v-model="state.form.payCycle" :options="PAY_CYCLE"></x-select>
        <x-input v-model="state.form.leaseTerm" label="收款期数">
          <view slot="suffix">期</view>
        </x-input>
        <x-input v-model="state.form.termAmount" label="每期金额">
          <view slot="suffix" style="width: 80rpx;text-align: right">元/{{ payCycleDesc }}</view>
        </x-input>
        <x-input v-if="productConfig.openOtherFee" v-model="state.form.otherFees" label="其它费用">
          <view slot="suffix">元</view>
        </x-input>
        <x-datetime label="起租日期" returnType="string" v-model="state.form.leaseStartDate" :border="false" type="date"></x-datetime>
      </x-box>
    </view>

    <view class="box">
      <x-box title="收款设置">
        <x-cell titleWidth="180rpx">
          <view slot="title" class="x-label">到期自动代扣</view>
          <view slot="value">
            <x-radio-button v-model="state.form.sysWithhold" align="right" :list="AUTO_WITHHOLDING"></x-radio-button>
          </view>
        </x-cell>
        <x-cell title="押金类型" :desc="depositDesc">
          <view slot="value">
            <x-radio-button v-model="state.form.depositType" align="right" :list="productConfig.depositTypeDict"></x-radio-button>
          </view>
        </x-cell>
        <x-input v-model="state.form.deposit" label="押金金额">
          <view slot="suffix">元</view>
        </x-input>
        <x-cell :border="false" desc="提示：订单确认后，用户就需支付首期金额和其他费用。" title="交租类型">
          <view slot="value">
            <x-radio-button  v-model="state.form.rentPaymentType" align="right" :list="PAY_RENT"></x-radio-button>
          </view>
        </x-cell>
      </x-box>
    </view>

    <view class="box">
      <x-box title="订单备注">
        <view class="x-container" style="padding-bottom: 30rpx">
          <view class="textarea">
            <textarea v-model="state.form.orderRemark" placeholder-style="font-size: 28rpx"
                      placeholder="简单说明下订单简要概况"></textarea>
          </view>
        </view>
      </x-box>
    </view>
    <view class="box x-inner-normal-bottom" v-if="productConfig.openSwitchServiceFee">
      <x-box title="平台服务费">
        <view class="service-fee x-container">
          <view class="desc">本次创建订单，需支付
            <text style="color: #FF8900">{{ companyConfig.orderFeeAmount }}元</text>
            平台服务费
          </view>
          <view class="x-row">
            <view @click="state.form.serviceFeePayer = 1" class="radio"
                  :class="{'active': state.form.serviceFeePayer == 1, 'normal': state.form.serviceFeePayer != 1}">商家支付
            </view>
            <view @click="state.form.serviceFeePayer = 2" class="radio"
                  :class="{'active': state.form.serviceFeePayer == 2, 'normal': state.form.serviceFeePayer != 2}">用户支付
            </view>
          </view>
          <view class="note">提示：用户扫码授权后，自动用支付宝账号({{companyInfo.alipayAccount}})支付</view>
        </view>
      </x-box>
    </view>
  </x-main>

  <x-order-qrcode @close="onClose" ref="orderQrcodeRef"></x-order-qrcode>

  <x-popup :height="880" title="订单信息预览" v-model="state.show.preview">
    <view>
      <x-preview :data="state.previewData" :columns="col"></x-preview>
      <view slot="bottom">
        <x-bottom>
          <view @click="onSubmit" class="x-btn x-btn-primary">创建订单二维码</view>
        </x-bottom>
      </view>
    </view>
  </x-popup>
  <x-bottom>
    <view @click="onCreate" class="x-btn x-btn-primary">创建订单二维码</view>
  </x-bottom>
</template>

<script setup>
import XRadioButton from '@/components/form/radioButton'
import XPopup from '@/components/lib/popup'
import XPreview from '@/components/lib/preview'
import XOrderQrcode from '@/components/logic/order/qrcode';
import {Helper, GlobalConfig, Constant} from "core";
const {productConfig} = storeToRefs(GlobalConfig());
import companyStore from '@/stores/modules/company';
import orderStore from '@/stores/modules/order';
import {computed, reactive, ref} from "vue";
import {storeToRefs} from "pinia";
import {onLoad} from "@dcloudio/uni-app";

const CompanyStore = companyStore();
const OrderStore = orderStore();
const {companyConfig, companyInfo} = storeToRefs(CompanyStore);
/** 预览字段 **/
const col = ref([
  {label: "收款标签", field: "orderTag"},
  {label: "收款周期", field: "payCycle"},
  {label: "收款期数", field: "leaseTerm"},
  {label: "每期金额", field: "termAmount"},
  {label: "押金金额", field: "deposit"},
  {label: "其他费用", field: "otherFees", check: () => {
    return productConfig.value.openOtherFee;
    }},
  {label: "起租日期", field: "leaseStartDate"},
  {label: "到期自动代扣", field: "sysWithhold"},
  {label: "交租类型", field: "rentPaymentType"},
  {label: "平台服务费", field: "orderFeeAmount", check: () => {
      return productConfig.value.openServiceFee;
    }, format: (c,d) => {
    let payerDesc = state.form.serviceFeePayer == 1 ? '商家支付' : "用户支付"
    return companyConfig.value.orderFeeAmount + "元(" + payerDesc + ")"
    }},
  {label: "备注", field: "orderRemark"},
])
const orderQrcodeRef = ref(null);
const state = reactive({
  show: {
    preview: false,
  },
  previewData: {
    orderTag: "",
  },
  form: {
    orderTag: 'HOUSE',
    storeId: "",
    payCycle: "MONTH",
    leaseTerm: "",
    termAmount: "",
    deposit: "0",
    otherFees: "0",
    leaseStartDate: Helper.formatDate(new Date(), 'yyyy-MM-dd'),
    orderRemark: "",
    sysWithhold: 1,
    depositType: "FREEZE",
    rentPaymentType: "USE_FIRST",
    serviceFeePayer: "1",
  },
  orderNo: "",
})

onLoad(async () => {
  //todo 提交前先判断是否有未支付的订单
  // if(productConfig.value.product == "zft") {
  //   let isOk = await OrderStore.checkSubmit();
  //   if(! isOk) {
  //     return;
  //   }
  // }

  //加载公司配置信息
  CompanyStore.getConfig();
})

/**
 * 订单创建预览
 */
const onCreate = () => {
  if(OrderStore.validate(state.form)) {
    let payCycle = Constant.PAY_CYCLE.find(x => x.value == state.form.payCycle);
    let orderTag = Constant.ORDER_TAG.find(x => x.value == state.form.orderTag);
    let auto = Constant.AUTO_WITHHOLDING.find(x => x.value == state.form.sysWithhold);
    let deposit = Constant.DEPOSIT_TYPE.find(x => x.value == state.form.depositType);
    let payRent = Constant.PAY_RENT.find(x => x.value == state.form.rentPaymentType);

    state.previewData = {
      orderTag: Helper.empty(orderTag) ? "" : orderTag.label,
      payCycle: Helper.empty(payCycle) ? "" : payCycle.label,
      leaseTerm: state.form.leaseTerm + "期",
      termAmount: state.form.termAmount + "元",
      deposit: state.form.deposit + "元" + ("（" + Helper.empty(deposit) ? "" : deposit.label + "）"),
      otherFees: state.form.otherFees + "元",
      leaseStartDate: state.form.leaseStartDate,
      orderRemark: state.form.orderRemark,
      sysWithhold: Helper.empty(auto) ? "" : auto.label,
      orderFeeAmount: companyConfig.value.orderFeeAmount + "元",
      rentPaymentType: Helper.empty(payRent) ? "" : payRent.label,
    }
    state.show.preview = true;
  }
}

/**
 * 订单提交生成二维码
 **/
const onSubmit = async () => {
  state.show.preview = false;
  state.form.serviceFee = companyInfo.value.orderFeeAmount;
  let orderNo = await OrderStore.submit(state.form);
  if(! Helper.empty(orderNo)) {
    state.orderNo = orderNo;

    if(state.form.serviceFeePayer == '1') {
      //直接发起免密，不管结果成功失败
      OrderStore.withholdServicefee(orderNo)
    }

    orderQrcodeRef.value.open(state.orderNo);
  }
}

/**
 * 计算收款周期单位
 * @type {ComputedRef<unknown>}
 */
const payCycleDesc = computed(() => {
  let payCycle = Constant.PAY_CYCLE.find(x => x.value == state.form.payCycle);
  if (!Helper.emptyJson(payCycle)) {
    return payCycle.label;
  }
  return "日";
})

const depositDesc = computed(() => {
  return state.form.depositType == Constant.DEPOSIT.FREE ? '提示：用户无需交押金，在合约结束后，如需用户需付款给您时，系统可以从签约用户收款。' : '提示：用户需要冻结信用金，在合约结束后，系统帮您全额或者部分金额退还给用户。'
})

/**
 * 关闭二维码，跳订单详情
 */
const onClose = () => {
  uni.redirectTo({
    url: "/pages/order/detail?orderNo=" + state.orderNo
  })
}
</script>

<style scoped lang="less">
.box {
  width: 100%;
  background-color: #ffffff;
  margin-top: 20rpx;
}

.control {
  padding: 20rpx;
  box-sizing: border-box;
}

.textarea {
  border: 1px solid #999999;
  border-radius: 10rpx;
  padding: 2px;
  box-sizing: border-box;
  margin-bottom: 20rpx;

  textarea {
    font-size: 28rpx;
    height: 120rpx;
  }
}

.service-fee {
  padding-bottom: 30rpx;
  box-sizing: border-box;

  .desc {
    font-size: 28rpx;
    color: #6a6a6a;
  }

  .radio {
    font-size: 28rpx;
    padding: 16rpx 30rpx;
    box-sizing: border-box;
    border-radius: 8rpx;
    margin: 20rpx 20rpx 20rpx 0;
  }

  .normal {
    border: 1px solid #6a6a6a;
    color: #6A6A6A;
  }

  .active {
    border: 1px solid @primary;
    color: @primary;
  }

  .note {
    font-size: 24rpx;
    color: #999999;
  }
}
</style>
